<?php
/*
 *      DB.php
 *      
 *      Copyright 2010 Rakitin Vitaliy <virak@ukr.net>
 *      
 *      This program is free software; you can redistribute it and/or modify
 *      it under the terms of the GNU General Public License as published by
 *      the Free Software Foundation; either version 2 of the License, or
 *      (at your option) any later version.
 *      
 *      This program is distributed in the hope that it will be useful,
 *      but WITHOUT ANY WARRANTY; without even the implied warranty of
 *      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *      GNU General Public License for more details.
 *      
 *      You should have received a copy of the GNU General Public License
 *      along with this program; if not, write to the Free Software
 *      Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 *      MA 02110-1301, USA.
 */

require_once($_SERVER['DOCUMENT_ROOT']."/config.php");
require_once($_SERVER['DOCUMENT_ROOT']."/classes/GUI/nwmsg.php");

class DB {
	public static $db;
	public static $error;
	public static $log;
	
	/****************************************************************/
	public static function setError($sMessage) {
		die(DB::$error = "Class DB: ".$sMessage);
	}
	
	
	/****************************************************************/
	public static function connect() {
		$server = "localhost";
		$db = "test";
		DB::$db = mysql_connect($server);
		if (!DB::$db) {
			echo "Ошибка подключения к серверу MySQL";
			exit;
		}
		// Соединились, теперь выбираем базу данных:
		if (!mysql_select_db($db)) {
			//echo "Ошибка подключения к серверу MySQL";
			echo mysql_error();
			exit;
		}
		
		//DB::$db = pg_connect("host=".PostgreHost." port=".PostgrePort." dbname=".PostgreDbName." user=".PostgreUser." password=".PostgrePass);
		//DB::$db = pg_connect("host=".PostgreHost." port=".PostgrePort." dbname=".PostgreDbName." user=".PostgreUser." password=".PostgrePass);
/*
		if (! DB::$db) {
			DB::setError('Unable to connect: '.pg_last_error());
		}
*/
	}
	/****************************************************************/
	public static function disconnect() {
		//pg_close(DB::$db);
		mysql_close(DB::$db);
	}
	/****************************************************************/
	public static function select($sQuery) {
		$oResult = DB::query($sQuery);
		if (!$oResult) { return false; }

		$aRecordSet = array();
		while ($aRow = mysql_fetch_assoc($oResult)) {
			$aRecordSet[] = $aRow;
		}
		mysql_free_result($oResult);
		return $aRecordSet;
	}
	/****************************************************************/
	public static function update($sQuery) {
		$oResult = DB::query($sQuery);
		return mysql_affected_rows($oResult);
	}
	/****************************************************************/
	public static function updateArray($sTable, $aValues) {
		if(!$aTableFields = DB::listFieldNames($sTable)) {
				return false;
		}
		$sQuery = 'UPDATE `'.$sTable.'` SET ';
		$aPairs = array();
		foreach($aValues as $sKey=>$sVal) {
				if(in_array($sKey, $aTableFields)) {
						$aPairs[] = $sKey.'="'.$sVal.'"';
				}
		}
		if(in_array('created', $aTableFields) && !isset($aValues['created']) ) {
						$aPairs[] = 'created=NOW()';
		}
		$sQuery .= implode(',', $aPairs);
		return DB::update($sQuery);
	}
	/****************************************************************/
/*
	public static function insert($sQuery) {
		$oResult = DB::query($sQuery);
		//if (!$oResult) { return false; }
		//return pg_insert_id(DB::$db);
		
	}
*/
	/****************************************************************/
/*
	public static function insertArray($sTable, $aValues) {
		if(!$aTableFields = DB::listFieldNames($sTable)) {
				return false;
		}
		$sQuery = 'INSERT INTO `'.$sTable.'` SET ';
		$aPairs = array();
		foreach($aValues as $sKey=>$sVal) {
				if(in_array($sKey, $aTableFields)) {
						$aPairs[] = $sKey.'="'.$sVal.'"';
				}
		}
		if(in_array('created', $aTableFields) && !isset($aValues['created']) ) {
						$aPairs[] = 'created=NOW()';
		}
		$sQuery .= implode(',', $aPairs);
		return DB::insert($sQuery);
	}
*/
	/****************************************************************/
	public static function recordExists($sTable, $sWhere) {
		$sQuery = 'SELECT COUNT(*) AS count FROM `'.$sTable.'` WHERE '.$sWhere;
		$oResult = DB::select($sQuery);
		return $oResult[0]['count'] > 0;
	}
	
	public static function tableExists($sTable) {
		$sQuery = "SELECT table_name FROM information_schema.tables WHERE table_name = '".$sTable."' AND table_schema='test';";
		$oResult = DB::select($sQuery);
		return count($oResult) == 1;
	}
	
	/****************************************************************/
	public static function recordsCount($sTable, $sWhere = NULL) {
		if (isset($sWhere)) {
			$sQuery = 'SELECT COUNT(*) AS count FROM '.$sTable.' WHERE '.$sWhere;
		} else {
			$sQuery = 'SELECT COUNT(*) AS count FROM '.$sTable;
		}
		$oResult = DB::select($sQuery);
		return $oResult[0]['count'];
	}
	/****************************************************************/
	public static function query($sQuery) {
		DB::$error = null;
		if(!DB::$db) {
			DB::connect();
			if(!DB::$db) {
				DB::setError('Query failed: not connected to database');
				return false;
			}
		}
		$oResult = mysql_query($sQuery, DB::$db);
		if (!$oResult) {
			//DB::setError('Query failed: ' . mysql_error());
			new nwmsg('Query failed: ' . mysql_error());
		}
		return $oResult;
	}
	/****************************************************************/
	public static function listFieldNames($sTable) {
		$aFields = DB::select('SHOW COLUMNS FROM '.$sTable);
		$aFieldNames = array();
		foreach($aFields as $aField) {
				$aFieldNames[] = $aField['Field'];
		}
		return $aFieldNames;
	}
	/****************************************************************/
}
?>
